from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.controllers.marketing.coupons import coupons_controller
from app.controllers.marketing.coupons_rule import coupons_rule_controller
from app.controllers.saas.pay import pay_controller
from app.schemas.saas import PayCreate
from app.settings import settings
from app.controllers.customer.users import users_controller
from app.controllers.orders.list import orders_list_controller
from app.models import OrdersList, Coupons, CouponsRole
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.orders import *
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID
from datetime import datetime

saas_pay_router = APIRouter()

@saas_pay_router.get("/list", summary=f"查看用户列表", dependencies=[DependCustomerAuth])
async def list_customer(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description="姓名/手机号"),
):
    q = Q()
    if name:
        q &= (Q(name__contains=name) | Q(phone__contains=name))
    total, customer_objs = await users_controller.list(page=page, page_size=page_size, search=q, order=["-last_login"] ,filed=["parent"])
    data = [await obj.to_dict(m2m=True,exclude_fields=["password"]) for obj in customer_objs]
    level_objs = await users_controller.level_list()
    for item in data:
        item["role_name"] = level_objs.get(item["role_id"], None)
        item["parent"] = item["parent_id"]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@saas_pay_router.get("/get", summary="查看会员详情")
async def get_customer(
        id: int = Query(..., description="会员id"),
):
    api_obj = await users_controller.get_detail(user_id=id)
    data = await api_obj.to_dict()
    return Success(data=data)



@saas_pay_router.post("/create", summary=f"创建订单", dependencies=[DependCustomerAuth])
async def do_orders_list_create(
        data_in: PayCreate,
):
    user_id = CTX_USER_ID.get()
    ret = await pay_controller.do_creat(data_in=data_in,add_uid=user_id)
    if ret["pay_status"] == 1:
        return Success(msg="下单成功", data=ret)
    else:
        return Fail(msg=ret["msg"])


@saas_pay_router.get("/coupons_list", summary=f"客户优惠券列表", dependencies=[DependCustomerAuth])
async def do_coupons_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_id: int = Query(0, description=f"用户id"),
):
    q = Q(is_used=0,user_id=user_id)
    total, data = await coupons_controller.do_list(page=page, page_size=page_size, search=q)
    type_objs = await coupons_rule_controller.level_list()
    for item in data:
        item['type_name'] = type_objs[item['coupons_id']]

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)